Javascript 简单实现Gzip 压缩字符串 基于pako.js |
您所在的位置:网站首页 › javascript 压缩字符串 › Javascript 简单实现Gzip 压缩字符串 基于pako.js |
申明,全篇内容都是基于pako.js来实现gzip压缩字符串,本文只是介绍简单用法 前言后端返回前端一般直接用Nginx或者Tomcat就可以自动实现Gzip, 但前端发送给后端就需要额外的代码实现, 这个就看需求了,如果需要发送大量可压缩率高的文本, 可以通过此方法实现前端JS压缩字符串, 再发送到后端服务器解压字符串。 在线演示DEMO地址: https://tczmh.gitee.io/gzipdemo/ GITEE源码地址: https://gitee.com/tczmh/GzipDemo 代码 测试Gzip 内容越长,重复率越高,压缩效果越好,如果字数过少,压缩率可能超过100% 原文: 压缩: 解压: 压缩率: function input() { const input = document.getElementById('input').value; const ys = zip(input); const jy = unzip(ys); document.getElementById('yw').innerText = input; document.getElementById('ys').innerText = ys; document.getElementById('jy').innerText = jy; document.getElementById('ysl').innerText = (Math.round(length(ys) / length(input) * 10000) / 100.00 + "%"); } // 解压 function unzip(b64Data) { let strData = atob(b64Data); const charData = strData.split('').map(function (x) { return x.charCodeAt(0); }); const binData = new Uint8Array(charData); const data = pako.inflate(binData); strData = String.fromCharCode.apply(null, new Uint16Array(data)); return decodeURIComponent(strData); } // 压缩 function zip(str) { const binaryString = pako.gzip(encodeURIComponent(str), {to: 'string'}) return btoa(binaryString); } // 占用字节数计算(UTF-8) function length(str) { let total = 0, charCode, i, len; for (i = 0, len = str.length; i < len; i++) { charCode = str.charCodeAt(i); if (charCode |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |